let express = require("express");
let mysql = require("mysql");
let form = require("formidable");
let cookie = require("cookie-parser");

// 配置数据库
let con = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "stu",
});
// 链接数据库
con.connect();
let app = express();
//使用
app.use(cookie());
let server = require("http").Server(app);
let io = require("socket.io")(server);
app.use(express.static("node_modules"));
app.use(express.static("images"));
app.use(express.static("font"));
app.set("view engine", "ejs");
app.set("views", "./views");
app.get("/index", (req, res) => {
  res.render("index",{data:""});
  res.end();
});

// 登录
app.get("/login", (req, res) => {
  res.render("login");
  res.end();
});
app.post("/dologin", (req, res) => {
  // 接收用户和密码
  let form2 = new form.IncomingForm();
  form2.parse(req, (err, fields) => {
    if (!err) {
      console.log(fields);
      let { username, password } = fields;
      // 把用户传递的用户名当做查询条件到账号存在
      let sql = "select * from user where name=?";
      let name = [username];
      let sql2 = mysql.format(sql, name);
      con.query(sql2, (err, results) => {
        console.log(results);
        if (results.length > 0 && password == results[0].password) {
          // 进入表示用户名和密码正确
          console.log("登陆成功");
          // 设置cookie保存用户名
          res.cookie("setcookiedata1", name);

          res.render("index", { data: results[0].name });

          res.end();
        } else {
          console.log("对不起,您输入的账号或密码不正确");
          res.end();
        }
      });
    }
  });
});

//退出登录路由
app.get("/out", (req, res) => {
  // let outuser=req.cookies.setcookiedata1;
  res.clearCookie("setcookiedata1");
  res.redirect("/index");
  res.end();
});



/* //历史记录
app.get("/lsjl", (req, res) => {
  sql = "select * from lt";
  con.query(sql, (err,  dui) => {
      if (!err) {
          // console.log( dui);
          res.json({ "lt":  dui })
      }
  })
  // res.end()
})
 */

server.listen(8090);
//连接socket.io服务
io.on("connection", (socket) => {
  //接收客户端发送的信息
  socket.on("h57071", (res) => {
    console.log(res);
    let {name,msg}=res;
    let sql = "insert into lt (name,text) value (?,?)"
        let sql2 = mysql.format(sql, [name,msg])
        con.query(sql2, (err, results) => {
          console.log(results);
            if (!err) {
                if (results.affectedRows > 0) {
                }
            }
        })
        // 查找所有聊天记录
       let sql3="select * from lt";
       con.query(sql3, (err, lts) => {
        // console.log(lts);
       //聊天记录发送给客户端
socket.broadcast.emit("111", lts);
      })


    //将客户端的信息广播到所有在当前频道号上的用户
    socket.broadcast.emit("h57071", res);
  });
  socket.on("haveout", (res) => {
    console.log(res);
    //将客户端的信息广播到所有在当前频道号上的用户
    socket.broadcast.emit("haveout", res);
  });
});


// 实现用户上线通知
var usocket = []; //全局变量
io.on("connection", function (socket) {
  console.log("a user connected");

  //监听join事件
  socket.on("join", function (name) {
    usocket[name] = socket;
    io.emit("join", name); //服务器通过广播将新用户发送给全体群聊成员
  });
 
  
  
});



